一、filter() 簡介
- 對陣列使用 filter() 方法,會產生一個新的陣列。
- 新的陣列的內容,是經由將原陣列中的元素代入到函式中,經過函式篩選後所得。
- 不會改變原陣列。
二、filter() 語法
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
- callback: 這個 callback 函式,會把陣列中的每一個元素當成參數,帶入 callback 函式中,回傳值 為 true 就會保留該元素至新陣列中,若回傳值為 false 則不保留,可傳入三個參數:
- element: 目前被處理中的陣列裡的元素。
- index(選擇性): 上述元素的索引值。
- array(選擇性): 使用 filter() 的陣列本身,即上述語法中的
arr
。
- thisArg:執行 callback 函式的 this 值(即參考的物件)。
語法的執行範例如下:
var animals = ['cat', 'goat', 'mouse', 'monkey', 'peacock'];
var newAnimals = animals.filter(function(animal){
return animal.length > 4;
});
console.log(newAnimals);// ["mouse","monkey","peacock"]
ES6 的寫法:
const animals = ['cat', 'goat', 'mouse', 'monkey', 'peacock'];
const newAnimals = animals.filter(animal => animal.length > 4);
console.log(newAnimals);// ["mouse","monkey","peacock"]
三、filter() 常見用法
過濾數字大小
const numArray = [1, 65, 32, 457, 7981, 1245]; function isBigEnough (value){ return value > 100; } const newNumArr = numArray.filter(isBigEnough); console.log(newNumArr);// [457,7981,1245]
過濾重複的值
const words = ['B', 'A', 'C', 'F', 'G', 'C', 'H', 'A']; let newWords = words.filter((element, index, array) => array.indexOf(element) === index); console.log(newWords); //["B","A","C","F","G","H"]
參考資料:
https://ithelp.ithome.com.tw/articles/10229458
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/filter